import os
import uuid
import base64
import requests
from datetime import datetime


def html_to_url(html_content):
    title = '新部署网页'
    i1 = html_content.find('<title>')
    if i1 >= 0:
        i2 = html_content.find('</title>')
        if i2 > i1 + 7:
            title = html_content[i1 + 7: i2]

    i1 = html_content.find('<html')
    i2 = html_content.find('</html>')
    if i1 < 0 or i2 < 0:
        return '非法HTML代码！（HTML代码必须以"<html"开头，以"</html>"结束）'

    html_content = '<!DOCTYPE html>' + html_content[i1: i2 + 7]
    html_content = base64.b64encode(html_content.encode()).decode()

    gitee_apikey = os.environ['gitee_apikey']
    file_path = datetime.now().strftime('%Y%m%d') + '/' + str(uuid.uuid4()).replace('-', '') + '.html'
    gitee_url = f'https://gitee.com/api/v5/repos/cubenet/htmls/contents/{file_path}'
    headers = {
        'Content-Type': 'application/json',
    }
    body = {
        'access_token': gitee_apikey,
        'content': html_content,
        'message': 'new file'
    }

    try:
        res = requests.post(gitee_url, headers=headers, json=body)
    except Exception as e:
        return '保存HTML文件失败：' + str(e)

    if res.status_code != 201:
        return '保存HTML文件失败!'

    url = f'<a href="/special/thirdfile/mcp-htmls/{file_path}" target="_blank">{title}</a>'
    return url

